//
//  HWGameCommunityTopView.swift
//  HWanGame
//
//  Created by 王昌健 on 2022/10/18.
//  Copyright © 2022 94Wan. All rights reserved.
//

import UIKit

class HWGameCommunityTopView: UIView {
    var icon:UIImageView!
    var nameLabel:UILabel!
    var peopleNum:UILabel!
    var timeLabel:UILabel!
    var followButton:UIButton!
    var tableView:UITableView!
    var tableViewProtocol = HWGameCommunityTopProtocol()
//    var lineView:UIView!
    var model:HWGameCommunityModel?{
        didSet {
            guard let md = model else { return }
            icon.kf.setImage(with: URL(string: md.icon))
            nameLabel.text = md.name
            peopleNum.text = "社区人数：\(md.guanzhu_num)"
            timeLabel.text = "最新发布时间 \(md.new_time)"
            tableViewProtocol.models = md.news
            tableView.snp.updateConstraints { make in
                make.height.equalTo(CGFloat((model?.news.count ?? 0)*31)*widthScale + 20*widthScale)
            }
            tableView.reloadData()
            
//            if model?.is_guanzhu == true {
//                followButton.setImage(UIImage(named: "communityFollowed"), for: .normal)
//            } else {
//                followButton.setImage(UIImage(named: "communityFollow"), for: .normal)
//            }
            followButton.isSelected = md.is_guanzhu
        }
    }
    var followButtonClick:((_:HWGameCommunityModel)->())?
    var didClickNews:((_:HWGameCommunityNewsModel)->())?
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initUI()
        initFrame()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension HWGameCommunityTopView {
    private func initUI() -> Void {
        
        icon = UIImageView()
        icon.layer.cornerRadius = 12*widthScale
        icon.layer.borderColor = UIColor.white.alpha(0.1).cgColor
        icon.layer.borderWidth = 1
        icon.layer.masksToBounds = true
        addSubview(icon)
        
        nameLabel = HWLabel.createBoldLabel(title: "", color: "#EEEEEE", font: 16*widthScale)
        addSubview(nameLabel)
        
        peopleNum = HWLabel.createLabel(title: "", color: "#F2F3F5", font: 11*widthScale)
        addSubview(peopleNum)
        
        timeLabel = HWLabel.createLabel(title: "", color: "#E4E5E6", font: 11*widthScale)
        addSubview(timeLabel)
        
        peopleNum.textColor = "#F2F3F5".toColor.alpha(0.5)
        tableView = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        tableView.delegate = tableViewProtocol
        tableView.dataSource = tableViewProtocol
        tableView.backgroundColor = .white
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 10
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.showsVerticalScrollIndicator = false
        tableView.layer.cornerRadius = 12*widthScale
        tableView.layer.masksToBounds = true
        addSubview(tableView)
        tableView.contentInsetAdjustmentBehavior = .never
        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }
        
//        lineView = UIView()
//        lineView.backgroundColor = .colorWithHexString(hexString: "#F7F7F7")
//        addSubview(lineView)
        
        followButton = UIButton(type: .custom)
        followButton.backgroundColor = .white.alpha(0.2)
        followButton.layer.cornerRadius = 15
        followButton.layer.masksToBounds = true
        followButton.setImage("Forum_join".toImage, for: .normal)
        followButton.setImage("Forum_joined".toImage, for: .selected)
        followButton.setTitleColor(.white, for: .normal)
        followButton.setTitleColor("#AEB0B3".toColor, for: .selected)
        followButton.setTitle("加入", for: .normal)
        followButton.setTitle("已加入", for: .selected)
        followButton.addTarget(self, action: #selector(followButtonClick(_:)), for: .touchUpInside)
        followButton.titleLabel?.font = 14.font_semiBold
        addSubview(followButton)
        
        self.tableViewProtocol.didClickRow = {
            self.didClickNews?($0)
        }
        
    }
    
    @objc func followButtonClick(_:UIButton) -> Void {
        self.followButtonClick?(model ?? HWGameCommunityModel())
    }
    
    private func initFrame() -> Void {
        icon.snp.makeConstraints { make in
            make.left.equalTo(18*widthScale)
            make.top.equalTo(48*widthScale)
            make.width.height.equalTo(54*widthScale)
        }
        
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(icon.snp.right).offset(9*widthScale)
            make.top.equalTo(icon)
            make.height.equalTo(20*widthScale)
        }
        
        peopleNum.snp.makeConstraints { make in
            make.left.equalTo(nameLabel)
            make.top.equalTo(nameLabel.snp.bottom).offset(2*widthScale)
            make.height.equalTo(15*widthScale)
        }
        
        timeLabel.snp.makeConstraints { make in
            make.left.equalTo(peopleNum)
            make.top.equalTo(peopleNum.snp.bottom).offset(2*widthScale)
            make.height.equalTo(15*widthScale)
        }
        
        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(12*widthScale)
            make.right.equalToSuperview().offset(-12*widthScale)
            make.top.equalTo(135*widthScale)
            make.height.equalTo(111*widthScale)
        }
        
//        lineView.snp.makeConstraints { make in
//            make.left.right.equalToSuperview()
//            make.top.equalTo(tableView.snp.bottom)
//            make.height.equalTo(2*widthScale)
//        }
        
        followButton.snp.makeConstraints { make in
            make.width.equalTo(70*widthScale)
            make.height.equalTo(30*widthScale)
            make.right.equalTo(-18*widthScale)
            make.centerY.equalTo(icon)
        }
        
    }
}

class HWGameCommunityTopProtocol: NSObject {
    var models:[HWGameCommunityNewsModel]?
    var didClickRow:((_:HWGameCommunityNewsModel)->())?
}

extension HWGameCommunityTopProtocol: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.didClickRow?(models?[indexPath.row] ?? HWGameCommunityNewsModel())
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return models?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = HWGameCommunityTopCell.cellWithTableView(tableView: tableView)
        cell.indexPath = indexPath
        cell.model = models?[indexPath.row]
        return cell
    }
    
    
}

class HWGameCommunityTopCell: UITableViewCell {
    var tagLabel:UILabel!
    var titleLabel:UILabel!
    var arrowImage:UIImageView!
    var indexPath:IndexPath?{
        didSet {
            
        }
    }
    var model:HWGameCommunityNewsModel? {
        didSet {
            tagLabel.text = model?.type
            titleLabel.text = model?.title
//            if indexPath?.row == 0 {
//                tagLabel.backgroundColor = .colorWithHexString(hexString: "#AD52FF")
//            } else if indexPath?.row == 1 {
//                tagLabel.backgroundColor = .colorWithHexString(hexString: "#1CD67E")
//            } else if indexPath?.row == 2 {
//                tagLabel.backgroundColor = .colorWithHexString(hexString: "#FA8C08")
//            }
        }
    }
    class func cellWithTableView(tableView:UITableView) -> (HWGameCommunityTopCell) {
        let reUse:String = "HWGameCommunityTopCell"
        
        var cell = tableView.dequeueReusableCell(withIdentifier: reUse)
        
        if cell == nil {
            cell = HWGameCommunityTopCell.init(style: UITableViewCell.CellStyle.default, reuseIdentifier: reUse)
        }
        
        return cell as! HWGameCommunityTopCell
    }
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        initUI()
        initFrame()
    }
    
    func initUI() -> Void {
        selectionStyle = UITableViewCell.SelectionStyle.none
        backgroundColor = UIColor.clear
        
        tagLabel = HWLabel.createBoldLabel(title: "", color: "#FF7700", font: 11*widthScale)
        tagLabel.layer.cornerRadius = 2*widthScale
        tagLabel.layer.borderWidth = 1
        tagLabel.layer.borderColor = "#FF7700".toColor.cgColor
        tagLabel.textAlignment = .center
        tagLabel.layer.masksToBounds = true
        contentView.addSubview(tagLabel)
        
        titleLabel = HWLabel.createLabel(title: "", color: "#333333", font: 13*widthScale)
        contentView.addSubview(titleLabel)
        
        arrowImage = UIImageView()
        arrowImage.image = UIImage(named: "blackRightArrow")
        contentView.addSubview(arrowImage)
    }
    
    func initFrame() -> Void {
        tagLabel.snp.makeConstraints { make in
            make.left.equalTo(18*widthScale)
            make.top.equalTo(13*widthScale)
            make.width.equalTo(31*widthScale)
            make.height.equalTo(18*widthScale)
            make.bottom.equalTo(0).priority(.high)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(tagLabel.snp.right).offset(7*widthScale)
            make.right.equalTo(arrowImage.snp.left).offset(-10*widthScale)
            make.height.equalTo(18*widthScale)
            make.centerY.equalTo(tagLabel)
        }
        
        arrowImage.snp.makeConstraints { make in
            make.right.equalTo(-18*widthScale)
            make.width.height.equalTo(13*widthScale)
            make.centerY.equalTo(tagLabel)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
